<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑考试' : '新增考试' }}</span>
          <el-button @click="goBack" type="text">返回</el-button>
        </div>
      </template>

      <el-form ref="examFormRef" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="考试名称" prop="title">
                  <el-input v-model="form.title" placeholder="请输入考试名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="考试类型" prop="type">
                  <el-select v-model="form.type" placeholder="请选择考试类型" style="width: 100%">
                    <el-option label="期中考试" value="MIDTERM" />
                    <el-option label="期末考试" value="FINAL" />
                    <el-option label="随堂测验" value="QUIZ" />
                    <el-option label="作业" value="HOMEWORK" />
                    <el-option label="模拟考试" value="MOCK" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="关联课程" prop="courseId">
                  <el-select v-model="form.courseId" placeholder="请选择关联课程" style="width: 100%">
                    <el-option
                      v-for="course in courses"
                      :key="course.id"
                      :label="course.title"
                      :value="course.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="考试状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio value="DRAFT">草稿</el-radio>
                    <el-radio value="PUBLISHED">已发布</el-radio>
                    <el-radio value="CLOSED">已关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="考试描述" prop="description">
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入考试描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 时间设置 -->
          <el-tab-pane label="时间设置" name="time">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="form.startTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="form.endTime"
                    type="datetime"
                    placeholder="请选择结束时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="考试时长" prop="duration">
                  <el-input-number v-model="form.duration" :min="1" controls-position="right" style="width: 100%" />
                  <span style="margin-left: 8px;">分钟</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="允许迟到" prop="allowLateEntry">
                  <el-input-number v-model="form.allowLateEntry" :min="0" controls-position="right" style="width: 100%" />
                  <span style="margin-left: 8px;">分钟</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 考试设置 -->
          <el-tab-pane label="考试设置" name="settings">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="总分" prop="totalScore">
                  <el-input-number v-model="form.totalScore" :min="1" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="及格分数" prop="passScore">
                  <el-input-number v-model="form.passScore" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大尝试次数" prop="maxAttempts">
                  <el-input-number v-model="form.maxAttempts" :min="1" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="题目顺序" prop="questionOrder">
                  <el-radio-group v-model="form.questionOrder">
                    <el-radio value="FIXED">固定顺序</el-radio>
                    <el-radio value="RANDOM">随机顺序</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="显示分数">
                  <el-switch v-model="form.showScore" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="显示答案">
                  <el-switch v-model="form.showAnswer" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="允许回看">
                  <el-switch v-model="form.allowReview" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="防作弊模式">
                  <el-switch v-model="form.antiCheat" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="摄像头监控">
                  <el-switch v-model="form.cameraMonitor" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="屏幕录制">
                  <el-switch v-model="form.screenRecord" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 题目配置 -->
          <el-tab-pane label="题目配置" name="questions">
            <div class="question-config">
              <div class="config-header">
                <h4>题目类型配置</h4>
                <el-button type="primary" size="small" @click="addQuestionType">添加题型</el-button>
              </div>
              
              <div class="question-types">
                <div 
                  v-for="(questionType, index) in form.questionTypes"
                  :key="index"
                  class="question-type-item"
                >
                  <el-card>
                    <div class="type-header">
                      <span>题型 {{ index + 1 }}</span>
                      <el-button type="danger" size="small" @click="removeQuestionType(index)">删除</el-button>
                    </div>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="题目类型">
                          <el-select v-model="questionType.type" placeholder="请选择题目类型" style="width: 100%">
                            <el-option label="单选题" value="SINGLE_CHOICE" />
                            <el-option label="多选题" value="MULTIPLE_CHOICE" />
                            <el-option label="判断题" value="TRUE_FALSE" />
                            <el-option label="填空题" value="FILL_BLANK" />
                            <el-option label="简答题" value="SHORT_ANSWER" />
                            <el-option label="编程题" value="CODING" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="题目数量">
                          <el-input-number v-model="questionType.count" :min="1" controls-position="right" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="每题分数">
                          <el-input-number v-model="questionType.score" :min="1" controls-position="right" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-card>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getExamDetail, 
  createExam, 
  updateExam, 
  getCourseList
} from '@/api/exam'

const route = useRoute()
const router = useRouter()

// 响应式数据
const examFormRef = ref()
const loading = ref(false)
const activeTab = ref('basic')
const courses = ref([])

// 表单数据
const form = reactive({
  id: undefined,
  title: '',
  type: 'QUIZ',
  courseId: undefined,
  status: 'DRAFT',
  description: '',
  startTime: null,
  endTime: null,
  duration: 60,
  allowLateEntry: 0,
  totalScore: 100,
  passScore: 60,
  maxAttempts: 1,
  questionOrder: 'FIXED',
  showScore: true,
  showAnswer: false,
  allowReview: true,
  antiCheat: false,
  cameraMonitor: false,
  screenRecord: false,
  questionTypes: []
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入考试名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择考试类型', trigger: 'change' }
  ],
  courseId: [
    { required: true, message: '请选择关联课程', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' }
  ]
})

// 获取课程列表
const loadCourses = async () => {
  try {
    const response = await getCourseList()
    if (response.code === 200) {
      courses.value = response.data
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

// 获取考试详情
const loadExamDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const response = await getExamDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(form, response.data)
      // 处理日期格式
      if (form.startTime) form.startTime = new Date(form.startTime)
      if (form.endTime) form.endTime = new Date(form.endTime)
    }
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
  }
}

// 添加题型
const addQuestionType = () => {
  form.questionTypes.push({
    type: 'SINGLE_CHOICE',
    count: 1,
    score: 5
  })
}

// 删除题型
const removeQuestionType = (index) => {
  form.questionTypes.splice(index, 1)
}

// 提交表单
const submitForm = () => {
  examFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const formData = { ...form }
        // 处理日期格式
        if (formData.startTime) formData.startTime = formData.startTime.toISOString()
        if (formData.endTime) formData.endTime = formData.endTime.toISOString()
        
        if (isEdit.value) {
          await updateExam(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createExam(formData)
          ElMessage.success('创建成功')
        }
        goBack()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  examFormRef.value?.resetFields()
  form.questionTypes = []
}

// 返回列表
const goBack = () => {
  router.push('/exam/exam')
}

// 页面加载
onMounted(async () => {
  await loadCourses()
  await loadExamDetail()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-config {
  .config-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h4 {
      margin: 0;
    }
  }
  
  .question-types {
    .question-type-item {
      margin-bottom: 16px;
      
      .type-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        font-weight: 600;
      }
    }
  }
}
</style>
